import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElMessageBox,
  ElMessage,
  ElButton,
  ElIcon
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import TourPlanCompile from './compile'
import { handleTrim } from '~/utils/util'

import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { personInChargeEnum } from '~/store/oam/tour/typings'
import type { ValuesType, TourPlanStateType } from './typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'

export default defineComponent(function plan() {
  const store = useStore()
  const route = useRoute()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const state = reactive<TourPlanStateType>({})
  const tourState = useVuexGetters('tour', ['personInChargeOpt', 'designateOpt'])
  const userState = useVuexGetters('user', ['permission'])
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '巡视分组名称',
      prop: 'name',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '责任人',
      prop: 'leadUserName',
      minWidth: 160
    },
    {
      label: '巡视类型',
      prop: 'typeName',
      showOverflowTooltip: true,
      minWidth: 200
    },
    {
      label: '区域数量',
      prop: 'assetCounts',
      minWidth: 160,
      align: 'center'
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 220
    },
    {
      label: '计划开始时间',
      prop: 'beginTime',
      minWidth: 220
    },
    {
      label: '计划结束时间',
      prop: 'endTime',
      minWidth: 220
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 300,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('produce_patrol_group_view') && (
            <ElLink type="primary" onClick={() => compile('read', row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情
            </ElLink>
          )}
          {userState.permission.value.has('produce_patrol_group_update') && (
            <ElLink type="primary" onClick={() => compile('update', row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('produce_patrol_group_remove') && (
            <ElLink type="primary" onClick={() => remove(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    store.dispatch('tour/GetPatrolHandleUser')
    const { code, data } = await store.dispatch('tour/GetConfigList')
    if (code === 200) {
      if (data.length > 0) {
        proSaasTableRef.value!?.toSearch()
      }
    }
    const res = await store.dispatch('user/GetCurrentTenant')
    if (res.code === 200) {
      window.localStorage.setItem('userinfo', JSON.stringify(res.data))
    }

    if (route.query.type === 'add') {
      compile('add')
    }
  })
  //  编辑、新增、详情
  const compile = (type: TourPlanStateType['activeType'], row?: ValuesType) => {
    state.activeId = row?.id
    state.activeType = type
    // router.push({ path: '/oam/tour/plan/compile', query: { id: row?.id, type } })
  }
  //  删除
  const remove = (row: ValuesType) => {
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('tour/GetPatrolGroupRemoveList', row.id).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.toSearch()
            ElMessage({ type: 'success', message: '操作成功' })
          }
        })
      })
      .catch(() => {})
  }
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    if (state.activeType) {
      return (
        <TourPlanCompile
          id={state.activeId}
          type={state.activeType}
          goBack={() => compile(undefined)}
        />
      )
    }

    return (
      <ElCard shadow="never" class="covered-with-content">
        <ProSaasTable<ValuesType>
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{
            name:
              formValues.name === '' ? undefined : formValues.name && handleTrim(formValues.name)
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="tour/GetPatrolGroupList"
          searchformResponsiveCol={[
            <ElFormItem key="leadUserName" prop="leadUserName" label="">
              <ElSelect
                v-model={formValues.leadUserName}
                clearable
                onChange={clearSearchTable}
                placeholder="责任人"
              >
                {tourState.personInChargeOpt?.value?.map((item: personInChargeEnum) => (
                  <ElOption key={item?.id} label={item?.realName} value={item?.realName} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="name" prop="name" label="">
              <ElInput
                v-model={formValues.name}
                placeholder="巡视分组名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>
          ]}
          headerTitle={
            <>
              {userState.permission.value.has('produce_patrol_group_add') && (
                <ElButton type="primary" onClick={() => compile('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
            </>
          }
        />
      </ElCard>
    )
  }
})
